package com.yn.xgame.logic.handler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yn.xgame.DBHandler;
import com.yn.xgame.logic.DbServer;
import com.yn.xgame.logic.util.CheckUtils;
import com.yn.xgame.logic.util.GenUtils;
import com.yn.xgame.logic.util.MD5Utils;
import com.yn.xgame.message.C2GPbRedirectMessage;
import com.yn.xgame.pb.ClientGateProto;

public class RegistHandler extends DBHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(DbServer.class);

	public RegistHandler(QueryRunner runner,Connection conn){
		m_runner=runner;
		m_conn=conn;
	}
	
	@Override
	public Logger logger() {
		return null;
	}
	
	public Pair<Integer, String> regist(C2GPbRedirectMessage msg){
		ClientGateProto.Regist regist=msg.getPb().getRegist();
		String username=regist.getUsername();
		String nickname=regist.getNickname();
		String password=regist.getPassword();
		String phoneno=regist.getPhoneno();
		if(!CheckUtils.checkUserName(username)||!CheckUtils.checkNickName(nickname)||!CheckUtils.checkPassword(password)||!CheckUtils.checkMobilePhoneNo(phoneno)){
			return Pair.of(4, null);
		}
		try{
			password=MD5Utils.encryptTohex(password);
			m_conn.setAutoCommit(false);
			m_conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
			Map<String, Object> result = queryOne("select count(user_id) as c from user where user_name=?", new Object[]{username});
			long count = getLong(result, "c");
			if(count > 0){ //用户名重复
				return Pair.of(2, null);
			}
			result=queryOne("select count(user_id) as c from user where user_nickname=?", new Object[]{nickname});
			count = getLong(result, "c");
			if(count>0){ //昵称重复
				return Pair.of(3, null);
			}
			long userCode = 0; 
			int prefix = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
			String sql="select count(id) as c from account where prefix=?";
			result = queryOne(sql, new Object[]{prefix});
			count = getLong(result, "c");
			count++;
			int beginNum = 1;
			for (int i = 0; i < 8; i++) {
				beginNum *= 10;
			}
			if (count < beginNum) {
				userCode = prefix * beginNum + count;
			} else {
				long count8 = queryOne(sql, Long.class, new Object[]{8});
				count8++;
				if (count8 < beginNum) {
					prefix = 8;
					userCode = prefix * beginNum + count8;
				} else {
					long count9 = queryOne(sql, Long.class, new Object[]{9});
					count9++;
					if (count9 < beginNum) {
						prefix = 9;
						userCode = prefix * beginNum + count9;
					}
				}

			}
			String sql2="insert into account(prefix) values(?)";
			int result0=saveUpdate(sql2, new Object[]{prefix});
			String sql3="insert into user(user_name,user_nickname,user_pwd,user_code,user_tel,user_created) values(?,?,?,?,?,?)";
			int result1=saveUpdate(sql3, new Object[]{username,nickname,password,userCode,phoneno,new Date()});
			String sql4="insert into login_history(username,success,token,type) values(?,?,?,?)";
			String token=GenUtils.genUserToken(username);
			int result2=saveUpdate(sql4, new Object[]{username,"1",token,3});
			m_conn.commit();
			if(result0>0&&result1>0&&result2>0){
				return Pair.of(1,token);
			}else{
				return Pair.of(0, null);
			}
		}catch(Exception e){
			logger.error(e.getMessage());
			if(e instanceof SQLException){
				return Pair.of(5, null);
			}
			try{
				m_conn.rollback();
			}catch(SQLException e1){
				logger.error(e1.getMessage());
			}
			return Pair.of(6, null);
		}finally{
			try {
				m_conn.setAutoCommit(true);
			} catch (SQLException e) {
				logger.error(e.getMessage());
			}
		}
	}

}
